package com.kuang.demo.service.wx;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kuang.demo.bean.wx.*;
import com.kuang.demo.bo.wx.CommentBo;
import com.kuang.demo.bo.wx.OrderSubmitBo;
import com.kuang.demo.mapper.GoodsProductMapper;
import com.kuang.demo.mapper.OrderMapper;
import com.kuang.demo.mapper.wx.*;
import com.kuang.demo.pojo.wx.Cskaoyanmall_address;
import com.kuang.demo.vo.OrderDetailVO;
import com.kuang.demo.vo.wx.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service

public class WxOrderServiceImp implements WxOrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderGoodsMapper orderGoodsMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    WxAddressMapper wxAddressMapper;
    @Autowired
    Coupon4SubmitMapper coupon4SubmitMapper;
    @Autowired
    OrderGoods4SubmitMapper orderGoods4SubmitMapper;
    @Autowired
    Order4SubmitMapper order4SubmitMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;

    @Override
    public OrderListVo list(Map map) {
        //        Subject subject = SecurityUtils.getSubject();
        // TODO: 2020/11/5 从shio中取出userId

        //查找的订单类型
        int showType;
        try {
            showType = Integer.parseInt((String) map.get("showType"));
        } catch (Exception e) {
            showType = 0;
        }

        int page = Integer.parseInt((String) map.get("page"));
        int size = Integer.parseInt((String) map.get("size"));
        PageHelper.startPage(page, size);

        //根据userId,showType查找订单数组
        List<Order4ListVo> orderList = orderMapper.queryOrderListByUserId(1, showType);
        for (Order4ListVo order : orderList) {
            //根据订单的orderId查找订单包含的goods数组
            List<Goods4OrderListVo> goodsList4Orders = orderGoodsMapper.queryGoodsListByOrderId(order.getId());
            order.setGoodsList(goodsList4Orders);
        }

        //取出分页查找的总记录数
        PageInfo<Order4ListVo> order4ListVoPageInfo = new PageInfo<>(orderList);
        int total = (int) order4ListVoPageInfo.getTotal();

        return new OrderListVo(total, ((total) / size) + 1, orderList);
    }

    @Override
    public OrderDetailVo detail(Integer orderId) {
        Order4DetailVo order4DetaileVo = orderMapper.queryOrderDetailById(orderId);
        List<Goods4OrderDetailVo> goods4OrderDetailVo = orderGoodsMapper.queryGoodsList4OrderDetailByOrderId(orderId);
        return new OrderDetailVo(order4DetaileVo, goods4OrderDetailVo);
    }

    @Override
    public void cancel(Integer orderId) {
        orderMapper.cancelOrderById(orderId);
    }

    @Override
    public void refund(int orderId) {
        orderMapper.refundOrderById(orderId);
    }

    @Override
    public void delete(int orderId) {
        orderMapper.deleteOrderById(orderId);
        orderGoodsMapper.deleteOrderById(orderId);
    }

    @Override
    public void confirm(int orderId) {
        orderMapper.confirmOrderById(orderId);
    }

    @Override
    public Goods4CommentVo goods(Integer orderId, Integer goodsId) {
        Goods4CommentVo goods4CommentVo =
                orderGoodsMapper.queryOrderGoodsByOrderIdAndGoodsId(orderId, goodsId);
        return goods4CommentVo;
    }

    @Override
    public void comment(CommentBo commentBo) {
        // TODO: 2020/11/6 shiro取出UserId 并赋值给comment
        Comment comment = new Comment(null, commentBo.getOrderGoodsId(), 0, commentBo.
                getContent(), 1, commentBo.isHasPicture(), commentBo.getPicUrls(),
                commentBo.getStar(), new Date(), new Date(), false);
        //插入
        int insert = commentMapper.insert(comment);
        orderGoodsMapper.updateCommentByorderGoodsId(comment.getId(), comment.getValueId());
    }

    @Override
    public int submit(OrderSubmitBo orderSubmitBo) {
        String OrderSn = WxOrderServiceImp.getDate();
        double goodsPrice = 0;
        //运费都是8块，找不到运费在哪查啊。。。
        double freightPrice = 0;
        //查出地址信息
        Cskaoyanmall_address address = wxAddressMapper.selectById(orderSubmitBo.getAddressId());
        //查出cskaoyanmao_coupon表的coupon
        Coupon4Submit coupon = coupon4SubmitMapper.selectByPrimaryKey(orderSubmitBo.getCouponId());

        if (orderSubmitBo.getCartId() == 0) {
            //         TODO: 2020/11/6  shiro取出UserId 用来查询cart表的数据

            //根据userId取出cskaoyanmao_cart的list
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria().andUserIdEqualTo(1).andDeletedEqualTo(false);
            List<Cart> cartList = cartMapper.selectByExample(cartExample);
            for (Cart cart : cartList) {
                int number = goodsProductMapper.selectNumberById(cart.getProductId());
                if (cart.getNumber()>number) return 0;
                goodsPrice += cart.getPrice();
            }
            //创建待插入的订单
            if (goodsPrice- coupon.getDiscount()<88){
                freightPrice = 8;
            }
            Order4Submit order4Submit = new Order4Submit(null, 1, OrderSn, 101, address.
                    getName(), address.getMobile(), address.getAddress(), orderSubmitBo.getMessage(),
                    goodsPrice, freightPrice, coupon.getDiscount(), 0, 0, (goodsPrice + freightPrice - coupon.getDiscount()),
                    (goodsPrice + freightPrice - coupon.getDiscount()), null, null, null, null, null,
                    null, 0, null, new Date(), new Date(), false);

            //插入订单
            int insert = order4SubmitMapper.insert(order4Submit);
            for (Cart cart : cartList) {
                //待插入order_goods表的对象
                OrderGoods4Submit orderGoods4Submit = new OrderGoods4Submit(null,order4Submit.getId(),
                        cart.getGoodsId(),cart.getGoodsName(),cart.getGoodsSn(),cart.getProductId(),
                        cart.getNumber(),cart.getPrice(),cart.getSpecifications(),cart.getPicUrl(),0,
                        new Date(),new Date(),false);
                //插入order_goods表
                int insert1 = orderGoods4SubmitMapper.insert(orderGoods4Submit);
                //购物车删除商品
                int i = cartMapper.deleteByPrimaryKey(cart.getId());
            }
            return order4Submit.getId();
        } else {
            //根据cartId取出cskaoyanmao_cart的记录
            Cart cart = cartMapper.selectByPrimaryKey(orderSubmitBo.getCartId());
            int number = goodsProductMapper.selectNumberById(cart.getProductId());
            if (cart.getNumber()>number) return 0;
            goodsPrice = cart.getPrice();
            if (goodsPrice- coupon.getDiscount()<88){
                freightPrice = 8;
            }
            //创建待插入的订单
            Order4Submit order4Submit = new Order4Submit(null, 1, OrderSn, 101, address.
                    getName(), address.getMobile(), address.getAddress(), orderSubmitBo.getMessage(),
                    goodsPrice, freightPrice, coupon.getDiscount(), 0, 0, (goodsPrice + freightPrice - coupon.getDiscount()),
                    (goodsPrice + freightPrice - coupon.getDiscount()), null, null, null, null, null,
                    null, 0, null, new Date(), new Date(), false);
           //插入订单
            int insert = order4SubmitMapper.insert(order4Submit);

            //待插入order_goods表的对象
            OrderGoods4Submit orderGoods4Submit = new OrderGoods4Submit(null,order4Submit.getId(),
                    cart.getGoodsId(),cart.getGoodsName(),cart.getGoodsSn(),cart.getProductId(),
                    cart.getNumber(),cart.getPrice(),cart.getSpecifications(),cart.getPicUrl(),0,
                    new Date(),new Date(),false);
            int insert1 = orderGoods4SubmitMapper.insert(orderGoods4Submit);
            //购物车删除商品
            int i = cartMapper.deleteByPrimaryKey(cart.getId());
            return order4Submit.getId();
        }
    }

    @Override
    public void prepay(Integer orderId) {
        orderMapper.prepay(orderId);
    }


    public static String getDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmss");
        String dateString = formatter.format(currentTime);
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return dateString + str.toString();
    }
}
